package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;

/**
 * customer的业务实现层
 * 
 * @author 王文杰
 * @version 1.0, 2017-9-8 18:38:30
 */
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

	/** 注入dao */
	@Autowired
	private CustomerRepository customerRepository;
	
	/**
	 * @see cn.itcast.crm.service.CustomerService#findNoAssociationCustomers()
	 */
	@Override
	public List<Customer> findNoAssociationCustomers() {
		// fixedAreaid is null
		return customerRepository.findByFixedAreaIdIsNull();
	}

	/**
	 * @see cn.itcast.crm.service.CustomerService#findHasAssociationFixedAreaCustomers(String)
	 */
	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(String fixedAreaId) {
		// fixedAreaId 
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	/**
	 * @see cn.itcast.crm.service.CustomerService#associationCustomersToFixedArea(String, String)
	 */
	@Override
	public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {
		// 解除关联动作
		customerRepository.clearFixedAreaId(fixedAreaId);
		
		if(StringUtils.isBlank(customerIdStr)){
			return;
		}
		// 切割字符串 customerIdStr
		String[] str = customerIdStr.split(",");
		for (String idStr : str) {
			int id = Integer.parseInt(idStr);
			customerRepository.updateFixedAreaId(fixedAreaId,id);
		}
		
	}

	/**
	 * @see cn.itcast.crm.service.CustomerService#register(Customer)
	 */
	@Override
	public void register(Customer customer) {
		customerRepository.save(customer);
	}

	/**
	 * @see cn.itcast.crm.service.CustomerService#findByTelephone(String)
	 */
	@Override
	public Customer findByTelephone(String telephone) {

		return customerRepository.findByTelephone(telephone);
	}

	/**
	 * @see cn.itcast.crm.service.CustomerService#updateType(String)
	 */
	@Override
	public void updateType(String telephone) {

		customerRepository.updateType(telephone);
	}

}
